package com.renge.ossservice.service.impl;

import com.renge.ossservice.service.OSSService;
import com.renge.ossservice.utils.ConstantProoertiseUtils;
import com.renge.ossservice.utils.OssUploadUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Service
public class OSSServiceImpl implements OSSService {


    @Override
    public String upload(MultipartFile multipartFile) {
        String url="";  //上传的路径
        OssUploadUtils ossUploadUtils=null;
        try {
            //获得文件原名
            String originalFilename = multipartFile.getOriginalFilename();
            //对原名处理
            int index = originalFilename.trim().lastIndexOf(".");
            String extension=originalFilename.trim().substring(index);   //获得文件扩展名：如 .jpg
            //1 在文件名称里面添加随机唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            //2 把文件按照日期进行分类
            //获取当前日期
            //   2019/11/12
            String datePath = new DateTime().toString("yyyy/MM/dd");
            //拼接2019/11/12/ewtqr313401.jpg
            originalFilename=datePath+"/"+uuid+extension;
            //调用工具传入必要参数
            ossUploadUtils = new OssUploadUtils(ConstantProoertiseUtils.ENDPOINT, ConstantProoertiseUtils.KEYID, ConstantProoertiseUtils.KEYSECRET, ConstantProoertiseUtils.BUCKETNAME);
            //使用工具方法实现上传
            ossUploadUtils.uplpad(multipartFile.getInputStream(),originalFilename);
            //调用工具方法实现关闭流
            ossUploadUtils.close();
            //返回路径
            url="https://"+ConstantProoertiseUtils.BUCKETNAME+"."+ConstantProoertiseUtils.ENDPOINT+"/"+originalFilename;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            //调用工具方法实现关闭流
            ossUploadUtils.close();
        }

        return null;
    }
}
